 <?php

class Webkul_Marketplacepartner_Model_Marketplacepartner extends Varien_Object
{
	public function customQuery($query = '', $cnnType = 'read'){
		// Fetch write database connection that is used in Mage_Core module
		$db = Mage::getSingleton('core/resource')->getConnection('core_' . $cnnType);

		// Now $db is an instance of Zend_Db_Adapter_Abstract
		$queryResult = $db->query($query);
		return $queryResult;
	}

	public function isCustomerProduct($magentoProductId){
		$product = Mage::getResourceModel('marketplacepartner/marketplacepartner_product_collection')
											->addAttributeToSelect('*')
											->addAttributeToFilter('product_id', $magentoProductId)->load();
		foreach($product as $p){return $p->getId();}
	}
	
	
	public function isProductId($magentoProductId){
		$db = Mage::getSingleton('core/resource')->getConnection('core_write');
		$queryResult=$db->query("SELECT userid FROM ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_data WHERE mageproductid='".$magentoProductId."'");
		$row = $queryResult->fetch();
		$userid=$row['userid'];	
		return $userid;	
	}

	
	public function isCommission($magentoUserId){
		$db = Mage::getSingleton('core/resource')->getConnection('core_write');
		$queryResult=$db->query("SELECT commision FROM ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_saleperpartner WHERE mageuserid='".$magentoUserId."'");
		$row1 = $queryResult->fetch();
		$percent=$row1['commision'];
		return $percent;	
	}
	
	public function getPartnerProducts($partnerId,$pagesize,$currentpage){
		$data=array();
		$products = Mage::getModel('marketplacepartner/userdata')->getCollection()
											->addFieldToFilter('userid', array('eq' => $partnerId))
											->addFieldToFilter('mageproductid', array('neq' => '0'))
											->setOrder('mageproductid', 'ASC')
											->setPageSize($pagesize)
											->setCurPage($currentpage)
											->load();			
		$i=0;	
		foreach($products as $product){
			$data[$i]=array('mageproductid'=>$product->getmageproductid());
			$i++;
		}
		return $data;
	}

	public function getProductType($cpproductid){
		$db = Mage::getSingleton('core/resource')->getConnection('core_read');
		// Now $db is an instance of Zend_Db_Adapter_Abstract
		$queryResult = $db->query("SELECT * FROM ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_data where customerpartnerproductid='".$cpproductid."'")->fetch();
		return $queryResult;
	}
	public function isCustomerProducttemp($magentoProductId){
		$collection = Mage::getModel('marketplacepartner/userdata')->getCollection();
		$collection->getSelect()->where('mageproductid ='.$magentoProductId);
		foreach($collection as $record){
		$userid=$record->getuserid();
		}
		return array('productid'=>$magentoProductId,'userid'=>$userid);
	}
	
	private function uploadZipSample1($image, $customer_partner_product_id) {
		$max_size = 3670016; // the max. size for uploading
		$my_upload = Mage::getModel('marketplaceprofile/uploadzipsample');
		if (!is_dir(Mage::getBaseDir().'/media/customersproducts/')) {
			mkdir(Mage::getBaseDir().'/media/customersproducts/', 0755);
		}
		// "files" is the folder for the uploaded files
		$my_upload->upload_dir = Mage::getBaseDir().'/media/customersproducts/'.$customer_partner_product_id."/"; 
		$my_upload->extensions = array(".gif", ".jpg", ".jpeg",".png"); // specify the allowed extensions here
		$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
		$my_upload->the_temp_file = $image['tmp_name'];
		$my_upload->the_file = $image['name'];
		$my_upload->http_error = $image['error'];
		$my_upload->replace = true;  // because only a checked checkboxes is true
		// use this boolean to check for a valid filename
		$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "y"; 
		$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
		// new name is an additional filename information, use this to rename the uploaded file
		if($my_upload->upload($new_name)){return true;} 
		else{return $my_upload->show_error_string();}
	}
	
	private function uploadZip1($image, $customer_partner_product_id) {
		$max_size = "1113670016000"; // the max. size for uploading
		$my_upload = Mage::getModel('marketplaceprofile/uploadzip');
		if (!is_dir(Mage::getBaseDir().'/media/customersproducts/')){
			mkdir(Mage::getBaseDir().'/media/customersproducts/', 0755);
		}
		// "files" is the folder for the uploaded files
		$my_upload->upload_dir = Mage::getBaseDir().'/media/customersproducts/'.$customer_partner_product_id."/"; 
		$my_upload->extensions = array(".zip", ".ap", ".psd",".rar",".pdf"); // specify the allowed extensions here
		$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
		$my_upload->the_temp_file = $image['tmp_name'];
		$my_upload->the_file = $image['name'];
		$my_upload->http_error = $image['error'];
		$my_upload->replace = true;  // because only a checked checkboxes is true
		// use this boolean to check for a valid filename
		$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "y"; 
		$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
		// new name is an additional filename information, use this to rename the uploaded file
		if($my_upload->upload($new_name)){return true;}
		else{return $my_upload->show_error_string();}
	}
	
	public function deleteProduct($urlapp)
	{
	
		$urlapppart=explode('/id/',$urlapp);
		$write = Mage::getSingleton('core/resource')->getConnection('core_write');
		Mage::getModel('marketplacepartner/marketplacepartner_product')->load($urlapppart[1])->delete();
		$querydata=$write->query("delete from ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_data where customerpartnerproductid='".$urlapppart[1]."'");
		return 0;
	}
	
	public function deleteApprovedProduct($urlapp)
	{
		$urlapppart=explode('/id/',$urlapp);
		require_once Mage::getBaseDir('app').'/Mage.php';
		Mage :: app("default") -> setCurrentStore( Mage_Core_Model_App :: ADMIN_STORE_ID );
		Mage::getModel('catalog/product')->load($urlapppart[1])->delete();
		require_once Mage::getBaseDir('app').'/Mage.php';
		$write = Mage::getSingleton('core/resource')->getConnection('core_write');
		$readresult=$write->query("select customerpartnerproductid from ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_data where mageproductid='$urlapppart[1]'");
		$row = $readresult->fetch();
		Mage::getModel('marketplacepartner/marketplacepartner_product')->load($row['customerpartnerproductid'])->delete();
		$querydata=$write->query("delete from ".Mage::getConfig()->getTablePrefix()."marketplacepartner_entity_data where mageproductid='$urlapppart[1]'");	
		
		return 0;
	}
	
	public function editApprovedProduct($data,$id,$wholedata)
	{
		$productcity = Mage::getModel('catalog/product');
		$loadpro= $productcity->load($id);
		$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($id);
		$loadpro->setCategoryIds($data->getParam('category'));
		$loadpro->setName($data->getParam('name'));
		$loadpro->setDescription($data->getParam('description'));
		$loadpro->setShortDescription($data->getParam('short_description'));
		$loadpro->setsku($data->getParam('sku'));
		$loadpro->setPrice($data->getParam('price'));
		$loadpro->setWeight($data->getParam('weight'));			
		$loadpro->setwebkulshipingtype($data->getParam('shipping_type'));			
		$loadpro->setwebkulamountper($data->getParam('shipping_amount'));			
		$loadpro->save();
		$customcount= explode(',',$wholedata['customcountallid']);
		/*if(isset($customcount[0])){
			for($k=0; $k<count($customcount);$k++)
			{
			$childcount= explode(',',$wholedata['childper'.$customcount[$k]]);
			$cuarray=array();
			for($l=0;$l<count($childcount); $l++)
			{
				$cuarray[$l]=array( 'is_delete' =>0,
						'title'         =>$wholedata['vcustomtitle'.$customcount[$k].'cop'.$childcount[$l]],
						'price_type'    => $wholedata['vcustompricetype'.$customcount[$k].'cop'.$childcount[$l]],
						'price'         => $wholedata['vcustomprice'.$customcount[$k].'cop'.$childcount[$l]],
						 'sku'           => $wholedata['vcustomsku'.$customcount[$k].'cop'.$childcount[$l]],
						 'sort_order'        => $wholedata['vcustomsort'.$customcount[$k].'cop'.$childcount[$l]],
						'option_type_id'=> -1,
						);
			}
			$optionData    = array(	
							'is_require'        =>$wholedata['customrequired'.$customcount[$k]],
							'previous_group'    => '',
							'title'             => $wholedata['customtitle'.$customcount[$k]],
							'type'              => $wholedata['customtype'.$customcount[$k]],
							'price_type'        => 'fixed',
							'price'             => 0,
							'sort_order'        => $wholedata['customsort'.$customcount[$k]],
							'values'	=> $cuarray,
							);
					$loadpro->setHasOptions(1)->save();
					$option = Mage::getModel('catalog/product_option')->setProductId($loadpro->getId())->setStoreId($loadpro->getStoreId())->addData($optionData);
					$option->save();
					$loadpro->addOption($option);
					$loadpro->save(); 
			}
			}*/
		$target =Mage::getBaseDir().'/media/customersproducts/'.$id.'/';
		mkdir($target, 0777);
		if(isset($_FILES) && (count($_FILES) > 0)){
			foreach($_FILES as $image){
				if($image['name']!=""){
					$target1 = $target.$image['name']; 
					move_uploaded_file($image['tmp_name'],$target1);
					$loadpro->addImageToMediaGallery($target1, array ('image','small_image','thumbnail'), true, false);
					$loadpro->save(); 
				}       
			}
		}
		$qtyStock->setProductId($id)->setStockId(1);
		$qtyStock->setData('is_in_stock', 1); 
		$savedStock = $qtyStock->save();
		$qtyStock->load($savedStock->getId())->setQty($data->getParam('stock'))->save();
		return 0;
	}
	
	//ProductController functions Start
	
	public function getApprovedata($magentoUserId){
			$write = Mage::getSingleton('core/resource')->getConnection('core_write');
			$readresult=$write->query("SELECT attribute_set_id FROM ".Mage::getConfig()->getTablePrefix()."eav_attribute_set WHERE attribute_set_name='Default' AND entity_type_id=(SELECT entity_type_id FROM ".Mage::getConfig()->getTablePrefix()."eav_entity_type WHERE entity_type_code='catalog_product')")->fetch();
			return $readresult;
	
	}
	
	//ProductController functions End

}
